<?php

class IngresanteController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			//'accessControl', // perform access control for CRUD operations
			'rights',
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	/*
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','HTMLPerson','PersonSearch','admin','delete'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
*/
	//public function allowedActions() { return 'index'; }
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($persona_numerodocumento, $persona_tipodocumento_id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($persona_numerodocumento, $persona_tipodocumento_id),
		));
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param Person $model
	 */
	private function parseData(Persona $model)
	{
		if(isset($_POST['Persona']))
		{
			$model->attributes=$_POST['Persona'];
			
			if(trim($model->persona_fechanacimiento)!= '')
			{
				$model->persona_fechanacimiento = Yii::app()->dateFormatter->format('yyyy-MM-dd', CDateTimeParser::parse($model->persona_fechanacimiento, Yii::app()->locale->getDateFormat('calendar_short')));	
			}
			
			$direccion = new Direccion();
			$direccion->attributes=$_POST['Direccion'];
			
			if($model->isNewRecord)//nuevo
			{
				$model->persona_estado_id = AplicacionVariables::ESTADO_ACTIVO_ID;
				$direccion->direccion_creado_usuario_id = user()->getId();
				$direccion->direccion_creado = new CDbExpression('NOW()');
				
			}
			else 
			{
				$direccion->direccion_modificado_usuario_id = user()->getId();
				$direccion->direccion_modificado = new CDbExpression('NOW()');
			}
			$direccion->direccion_estado_id= AplicacionVariables::ESTADO_ACTIVO_ID;
			
			$tmpDireccion= array();
			array_push($tmpDireccion, $direccion);
			$model->direcciones = $tmpDireccion;
			
			$comunicacion = new Comunicacion();
			$comunicacion->attributes=$_POST['Comunicacion'];
			$tmpComunicacion = array();
			array_push($tmpComunicacion, $comunicacion);
			$model->comunicaciones = $tmpComunicacion;
			
			
			if($model->validate() && 
				$direccion->validate() && 
				$comunicacion->validate())
			{
				
				
				$transaction=$model->dbConnection->beginTransaction();
				
				try
				{
					$model->save();
					$transaction->commit();
	   				$this->redirect(array('view','persona_tipodocumento_id'=>$model->persona_tipodocumento_id, 'persona_numerodocumento'=>$model->persona_numerodocumento));	
				}
				catch(Exception $e)
				{
					//var_dump($e);
				    $transaction->rollBack();
				}
			}
			else //hay arrores
			{
				$model->addErrors($direccion->getErrors());
				$model->addErrors($comunicacion->getErrors());
				
				if(trim($model->persona_fechanacimiento)!= '')
				{
					$model->persona_fechanacimiento = Yii::app()->dateFormatter->format('dd/MM/yyyy', $model->persona_fechanacimiento);	
				}
			}
		}
		return $model;
	}
	
	
	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model= new Persona();
		
		$model = $this->parseData($model);
	 
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($persona_numerodocumento, $persona_tipodocumento_id)
	{
		
		$model=$this->loadModel($persona_numerodocumento,$persona_tipodocumento_id);
		
		
		$model = $this->parseData($model);
		
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($persona_numerodocumento, $persona_tipodocumento_id)
	{
		
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($persona_numerodocumento, $persona_tipodocumento_id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->actionAdmin();
	}
	
	/**
	 * Manages all models.
	 */
	public function actionOwner()
	{
		//$criteria = new CDbCriteria();
		//$criteria->join = "join tbl_rel_person_property rpp on t.person_id = rpp.pepr_property_id";
		
		
		//$model = Person::model()->findAll($criteria);
		
		//var_dump($model);exit;
		$model=new Person('search');
		
		
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Person']))
			$model->attributes=$_GET['Person'];
		$this->render('admin',array(
			'model'=>$model,
			'filterByTypePerson'=>'owner'
		));
	}
	
	
	

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
	
		
		$model=new Persona('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Person']))
			$model->attributes=$_GET['Person'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($persona_numerodocumento,$persona_tipodocumento_id)
	{
		$criteria = new CDbCriteria();
		$criteria->condition = 'persona_numerodocumento = :numDOC AND persona_tipodocumento_id = :tipoDOC';
		$criteria->params = array(':numDOC'=>$persona_numerodocumento,':tipoDOC'=>$persona_tipodocumento_id);
		$model=Persona::model()->find($criteria);//FIXME se puede mejorar a lo mejor usardo findByPK
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='person-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
/**
	 * get Person as html.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionHTMLPerson()
	{
		//fixme es un asco esto mejorar 
		
		
		
		if(isset($_POST['Person']))
		{
			$typeDocument = $_POST['Person']['person_typedocument_id'];
			$numberDocument = $_POST['Person']['person_numberdocument'];
		}
		
		$model = Person::model()->getPersonActives($typeDocument, $numberDocument); 
		if(count($model) != 0)
		{
			echo CHtml::activeHiddenField($model[0], 'person_id');
			$this->widget('zii.widgets.CDetailView', array(
					'data'=>$model[0],
						'attributes'=>array(
											'person_firstname',
											'person_lastname',
											'person_numberdocument',
											'typeDocument.typedocument_name',												),
			));
		}
		else
		{
			echo "<p>the person doesn't exist</p>";
		}
	}
	
	/**
	 * mejorar este asco :)
	 * Enter description here ...
	 * @param Array $arrayCommunication
	 */
	private function parseCommunication($arrayCommunication)
	{
		//var_dump($arrayCommunication);exit;
		$communications = array(); 
		
		foreach ($arrayCommunication['communication_data'] as $key => $value)
		{
			$modelCommunication = new Communication();
			
			$modelCommunication->communication_typecommunication_id = $arrayCommunication['communication_typecommunication_id'][$key];
			$modelCommunication->communication_categorycommunication_id = $arrayCommunication['communication_categorycommunication_id'][$key];    
			$modelCommunication->communication_data = $value;
			
			$modelCommunication->validate();
			
			array_push($communications, $modelCommunication);
		}
		return $communications;
	}
	
	
	private function parseCommunicationErrors($communications){
		$return = true;
		foreach ($communications as $communication)
		{
			$communication->validate();
			if($communication->hasErrors())
			{
				$return = false;
			}
		}
		return $return;
		
	}
	
	public function actionautocomplete()
	{
		$res =array();

		if (isset($_GET['term'])) 
		{
			//CONCAT(per.persona_numerodocumento, '-',tdo.tipodocumento_abreviacion) as id,
			$qtxt ="SELECT 
							per.persona_tipodocumento_id,
							per.persona_numerodocumento, 
							CONCAT(tdo.tipodocumento_abreviacion, ' ',per.persona_numerodocumento , ' ', per.persona_apellido, ' ', per.persona_nombres) as value   
					FROM tbl_persona per
					JOIN tbl_tipodocumento tdo ON per.persona_tipodocumento_id = tdo.tipodocumento_id 
					WHERE CONCAT(tdo.tipodocumento_abreviacion , ' ',per.persona_numerodocumento, ' ', per.persona_apellido, ' ', per.persona_nombres) LIKE :term";
			$command =Yii::app()->db->createCommand($qtxt);
			$command->bindValue(":term", '%'.$_GET['term'].'%', PDO::PARAM_STR);
			$res =$command->queryAll();
		}
		echo CJSON::encode($res);
		Yii::app()->end();
	}
	
	public function actionSearch()
	{
		$resultado = '';
		
		
		if(
			isset($_POST['Persona']['persona_tipodocumento_id']) 
			&& trim($_POST['Persona']['persona_tipodocumento_id']) != ''
			&& isset($_POST['Persona']['persona_numerodocumento'])
			&& trim($_POST['Persona']['persona_numerodocumento']) != ''
			)
		{
			$model = new Persona();
			$model->persona_tipodocumento_id = $_POST['Persona']['persona_tipodocumento_id'];
			$model->persona_numerodocumento = $_POST['Persona']['persona_numerodocumento'];
			
			$criteria = new CDbCriteria();
			$criteria->condition = "persona_estado_id = :estado AND persona_tipodocumento_id = :tipoDocumento AND persona_numerodocumento = :numeroDocumento";
			$criteria->params = array(
										':estado'=>AplicacionVariables::ESTADO_ACTIVO_ID,
										':tipoDocumento'=>$model->persona_tipodocumento_id,
										':numeroDocumento'=>$model->persona_numerodocumento
									);
			$tmpPerson = $model->find($criteria);
			
			if(!is_null($tmpPerson))
			{
				Yii::import('application.extensions.json.CArJSON');
				$json = new CArJSON();
				
				$relations = array('tipoDocumento');
				$attributes = array(
										'root' => null,//all
										'tipoDocumento' => array( 'tipodocumento_id', 'tipodocumento_abreviacion' ),
				);
				$resultado =  $json->toJSON($tmpPerson, $relations, $attributes);
			}
			else
			{
				$resultado = '{"error": {"message": "'.t('Persona no existe','persona_etiqueta').'"}}';
			}

		}
		else 
		{
			$resultado = '{"error": {"message": "'.t('Faltan Datos','persona_etiqueta').'"}}';
		}
		
		
		
		
		header('Content-type: application/json');
		echo $resultado;
		Yii::app()->end(); 
	}	
	
}
